// Copyright 2011, Vanya Davidenko.
// Кодировка файла: UTF-8. 
package info.iu9.red;


public class Submatch implements Cloneable {
  public Object clone() {
    try { return super.clone(); }
    catch(CloneNotSupportedException e) { assert false; return null; }
  }

  Submatch(final String string) {
    assert string != null;
    string_ = string;
  }

  Submatch(final String string, final int first, final int last) {
    this(string);
    set_first(first);
    set_last(last);
  }

  public String toString() {
    if ( isEmpty() ) {
      return "";
    }
    return string_.substring(first_, end());
  }

  public boolean isEmpty() {
    return first_ == DEFAULT && last_ == DEFAULT;
  }

  String string() {
    return string_;
  }

  int begin() {
    return first();
  }
  int end() {
    if ( last_ < 0 ) {
      return last_;
    }
    return string_.offsetByCodePoints(last_, 1);
  }

  int first() {
    return first_;
  }
  void set_first(final int first) {
    if ( first < 0 ) { throw new IllegalArgumentException(); }
    first_ = first;
  }

  int last() {
    return last_;
  }
  void set_last(final int last) {
    if ( last < 0 ) { throw new IllegalArgumentException(); }
    last_ = last;
  }

  public boolean equals(final Object o) {
    if ( o == null ) { return false; }
    if ( o == this ) { return true; }
    if ( o.getClass() != getClass() ) { return false; }

    final Submatch o_s = (Submatch)o;
    return o_s.first_ == first_ && o_s.last_ == last_ && o_s.string_ == string_;
  }

  private int first_ = DEFAULT;
  private int last_ = DEFAULT;
  private String string_;

  final static int DEFAULT = -1;
}
